var videoUtils = require("../../utils/videoUtil.js")
const app = getApp()

Page({

  data: {
    cover: "cover",
    videoId: "",
    src: "",
    videoInfo: {},
    userLikeVideo: false,

    commentsPage: 1,
    commentsTotalPage: 1,
    commentsList: [],
    soundPlay: false,
    tip:"开",
    placeholder: "说点什么..."
  },
  videoCtx: {

  },

  //初始化
  onLoad: function (params) {
    var me = this;
    //获取video上下文对象
    me.videoCtx = wx.createVideoContext("myVideo", me);
    //获取上个页面传来的参数
    var videoInfo = JSON.parse(params.videoInfo);
    //判断视频是横的还竖的
    var height = videoInfo.videoHeight;
    var width = videoInfo.videoWidth;
    var cover = "cover";
    if (width >= height) {
      cover = "";
    }
    //设置全局变量
    me.setData({
      videoId: videoInfo.id,
      src: app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo,
      cover: cover
    });
    var serverUrl = app.serverUrl;
    var user = app.getGlobalUserInfo();
    var loginUserId = "";
    if (user != null && user != undefined && user != '') {
      loginUserId = user.id;
    }
    //初始化视频相关信息
    wx.request({
      url: serverUrl + '/user/queryPublisher',
      method: 'GET',
      data:{
        'loginUserId':loginUserId,
        'videoId': videoInfo.id,
        'publisherUserId': videoInfo.userId
      },
      success: function (res) {
        console.log(res.data);
        var publisher = res.data.data.publisher;
        var userLikeVideo = res.data.data.userLikeVideo;
        me.setData({
          serverUrl: serverUrl,
          publisher: publisher,
          userLikeVideo: userLikeVideo
        });
      }
    })
    //初始化评论列表
    me.getCommentsList(1);
  },

  //页面处于显示状态
  onShow: function () {
    var me = this;
    me.videoCtx.play(); //开始播放
  },

  //页面处于隐藏状态
  onHide: function () {
    var me = this;
    me.videoCtx.pause(); //暂停播放
  },

  //搜索事件
  showSearch: function () {
    wx.navigateTo({
      url: '../searchVideo/searchVideo',
    })
  },

  //复用上传视频
  upload: function () {
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoinfo/videoinfo#videoInfo@' + videoInfo
    if (user == null || user == undefined || user == "") {
      wx.navigateTo({
        url: '../userLogin/userLogin?redirectUrl=' + realUrl,
      })
    } else {
      videoUtils.uploadVideo();
    }

  },

  //返回主页
  showIndex: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },

  //个人中心
  showMine: function () {
    var user = app.getGlobalUserInfo();
    if (user == null || user == undefined || user == "") {
      wx.navigateTo({
        url: '../userLogin/userLogin',
      })
    } else {
      wx.navigateTo({
        url: '../mine/mine',
      })
    }

  },

  //用户点赞视频或取消
  likeVideoOrNot: function () {
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = me.data.videoInfo;
    //判断用户是否登陆
    if (user == null || user == undefined || user == "") {
      wx.navigateTo({
        url: '../userLogin/userLogin',
      })
    } else {
      var userLikeVideo = me.data.userLikeVideo;
      var likeMethod = 'userLike';
      if (userLikeVideo) {
        likeMethod = 'userUnlike';
      }
      var serverUrl = app.serverUrl;
      var url = '/video/' + likeMethod;
      wx.showLoading({
        title: '...',
      })
      wx.request({
        url: serverUrl + url,
        method: 'GET',
        data: {
          userId: user.id,
          videoId: videoInfo.id,
          videoCreaterId: videoInfo.userId
        },
        header: {
          'content-type': 'application/json', // 默认值
          'headerUserId': user.id,
          'headerUserToken': user.userToken
        },
        success: function (res) {
          wx.hideLoading();
          me.setData({
            userLikeVideo: !userLikeVideo
          })
        }
      })
    }
  },

  //查看发布者信息
  showPublisher:function(){
    var me = this;
    var user = app.getGlobalUserInfo();
    var videoInfo = me.data.videoInfo;
    var realUrl = '../mine/mine#publisherId@' + videoInfo.userId;

    if (user == null || user == undefined || user == "") {
      wx.navigateTo({
        url: '../userLogin/login?redirectUrl='+realUrl,
      })
    } else {
      wx.navigateTo({
        url: '../mine/mine?publisherId=' + videoInfo.userId,
      })
    }
  },

  //分享事件
  shareMe: function () {
    var me = this;
    var user = app.getGlobalUserInfo();

    wx.showActionSheet({
      itemList: ['下载到本地', '举报用户', '分享到朋友圈', '分享到QQ空间', '分享到微博'],
      success: function (res) {
        console.log(res.tapIndex);
        if (res.tapIndex == 0) {
          // 下载
          wx.showLoading({
            title: '下载中...',
          })
          wx.downloadFile({
            url: app.serverUrl + me.data.videoInfo.videoPath,
            success: function (res) {
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                console.log(res.tempFilePath);
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function (res) {
                    console.log(res.errMsg)
                    wx.hideLoading();
                  }
                })
              }
            }
          })
        } else if (res.tapIndex == 1) {
          // 举报
          var videoInfo = JSON.stringify(me.data.videoInfo);
          var realUrl = '../videoinfo/videoinfo#videoInfo@' + videoInfo;

          if (user == null || user == undefined || user == '') {
            wx.navigateTo({
              url: '../userLogin/login?redirectUrl=' + realUrl,
            })
          } else {
            var publishUserId = me.data.videoInfo.userId;
            var videoId = me.data.videoInfo.id;
            var currentUserId = user.id;
            wx.navigateTo({
              url: '../report/report?videoId=' + videoId + "&publishUserId=" + publishUserId
            })
          }
        } else {
          wx.showToast({
            title: '官方暂未开放...',
          })
        }
      }
    })
  },

  //菜单右上分享
  onShareAppMessage: function (res) {

    var me = this;
    var videoInfo = me.data.videoInfo;

    return {
      title: '短视频内容分析',
      path: "pages/videoinfo/videoinfo?videoInfo=" + JSON.stringify(videoInfo)
    }
  },

  //评论按钮事件
  leaveComment: function () {
    this.setData({
      commentFocus: true
    });
  },

  //保存评论
  saveComment: function (e) {
    var me = this;
    var content = e.detail.value;
    if (content == null || content == "" || content == undefined){
      content = this.data.commentValue;
    }
    // 获取评论回复的fatherCommentId和toUserId
    var fatherCommentId = e.currentTarget.dataset.replyfathercommentid == undefined ? this.data.replyFatherCommentId : e.currentTarget.dataset.replyfathercommentid;
    var toUserId = e.currentTarget.dataset.replytouserid == undefined ? this.data.replyToUserId : e.currentTarget.dataset.replytouserid;
    debugger
    var user = app.getGlobalUserInfo();
    var videoInfo = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoinfo/videoinfo#videoInfo@' + videoInfo;

    if (user == null || user == undefined || user == '') {
      wx.navigateTo({
        url: '../userLogin/login?redirectUrl=' + realUrl,
      })
    } else {
      wx.showLoading({
        title: '请稍后...',
      })
      wx.request({
        url: app.serverUrl + '/video/saveComment?fatherCommentId=' + fatherCommentId + "&toUserId=" + toUserId,
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
          'headerUserId': user.id,
          'headerUserToken': user.userToken
        },
        data: {
          // fatherCommentId: fatherCommentId == null ? "" : fatherCommentId,
          // toUserId: toUserId == null ? "" : toUserId,
          fromUserId: user.id,
          videoId: me.data.videoInfo.id,
          comment: content
        },
        success: function (res) {
          console.log(res.data)
          wx.hideLoading();

          me.setData({
            contentValue: "",
            commentsList: [],
            //placeholder: "",
            replyFatherCommentId: "",
            replyToUserId: "",
            commentFocus: false
          });
          me.getCommentsList(1);
        }
      })
    }
  },

  //回复评论
  replyFocus: function (e) {
    var fatherCommentId = e.currentTarget.dataset.fathercommentid;
    var toUserId = e.currentTarget.dataset.touserid;
    var toNickname = e.currentTarget.dataset.tonickname;

    this.setData({
      placeholder: "回复  " + toNickname,
      replyFatherCommentId: fatherCommentId,
      replyToUserId: toUserId,
      commentFocus: true
    });
  },
  //获取评论列表
  getCommentsList: function (page) {
    var me = this;
    var videoId = me.data.videoInfo.id;
    wx.showLoading();
    wx.request({
      url: app.serverUrl + '/video/getVideoComments?videoId=' + videoId + "&page=" + page + "&pageSize=5",
      method: "POST",
      success: function (res) {
        console.log(res.data);
        wx.hideLoading();
        var commentsList = res.data.data.rows;
        var newCommentsList = me.data.commentsList;
        me.setData({
          commentsList: newCommentsList.concat(commentsList),
          commentsPage: page,
          commentsTotalPage: res.data.data.total
        });
      }
    })
  },

  //上拉加载
  onReachBottom: function () {
    var me = this;
    var currentPage = me.data.commentsPage;
    var totalPage = me.data.commentsTotalPage;
    if (currentPage === totalPage) {
      return;
    }
    var page = currentPage + 1;
    me.getCommentsList(page);
  },

  //输入框失焦，保存评论的值
  commontInputEvent: function (e) {
    this.setData({
      commentValue: e.detail.value
    })
  },
  
  //声音开关
  soundPaly:function(e){
    var soundflag = e.currentTarget.dataset.soundflag == 1 ? false: true; 
    this.setData({
      soundPlay: soundflag
    })
  }
})